#include <iostream>
#include <string>
#include <cstdio>
#include <mysql/mysql.h>

const std::string host = "127.0.0.1";
const std::string user = "baichen";
const std::string password = "!@#$%^&*()123aacS";
const std::string db = "test1";
const unsigned port = 8082;

int main()
{
    // std::cout << "mysql client Version:" << mysql_get_client_info() << std::endl;
    // 1. 创建句柄
    MYSQL *my = mysql_init(nullptr);
    // 2. 连接数据库
    if (mysql_real_connect(my, host.c_str(), user.c_str(), password.c_str(), db.c_str(), port, nullptr, 0) == nullptr)
    {
        std::cerr << "connect failed" << std::endl;
        return 1;
    }
    std::cout << "connect succeed" << std::endl;

    // 2.1 字体设置
    mysql_set_character_set(my, "utf8");

    // 3. 发送指令
    // std::string command = "insert into account values(9, \'h\', 99.99)";
    // std::string command = "delete from account where id=10";
    // std::string command = "update account set blance=88.88 where id=9";
    std::string command = "select * from account";
    int ret = mysql_query(my, command.c_str());
    if(ret != 0)
    {
        std::cerr << "execute failed: " << command << std::endl;
        return 2; 
    }
    std::cout << "execute succeed: " << command << std::endl; 

    // 3.1 结果解析
    MYSQL_RES* result = mysql_store_result(my);
    int row = mysql_num_rows(result);
    int col = mysql_num_fields(result);

    MYSQL_FIELD* fields = mysql_fetch_field(result);
    for(int i = 0; i < col; ++i)
    {
        std::cout << fields[i].name << "\t";
    }
    std::cout << std::endl;

    for(int i = 0; i < row; ++i)
    {
        // MYSQL_ROW 其实就是二维数组
        MYSQL_ROW text = mysql_fetch_row(result);
        for(int j = 0; j < col; ++j)
        {
            std::cout << text[j] << "\t";
        }
        std::cout << std::endl;
    }

    std::cout << std::endl;

    // 4. 关闭数据库
    // free(result);
    mysql_close(my);
    return 0;
}